package com.marcowu.study.spb.tracing.resource;

import com.marcowu.study.spb.tracing.manager.SampleManager;
import com.marcowu.study.spb.tracing.zipkin.TracerBuiler;
import io.opentracing.Scope;
import io.opentracing.Span;
import io.opentracing.Tracer;
import io.opentracing.tag.Tags;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Component
@RestController
@RequestMapping("/tracing")
public class SampleController {

  @Autowired
  private SampleManager sampleManager;

  private Tracer tracer = TracerBuiler.getZipkinTracer("zipkin-test");

  @GetMapping("/demo1")
  public String demo1() {
    String response;
    try (Scope scope = tracer.buildSpan("SaveBatchJob")
            .withTag(Tags.SPAN_KIND_CLIENT, "demo")
            .startActive(false)) {
      Span span = scope.span();
      span.setTag("user", "admin");
      try {
        response = sampleManager.getSample2(span);
      } catch (Exception e) {
        Tags.HTTP_STATUS.set(scope.span(), 500);
        throw e;
      }finally {
        span.finish();
      }
      return response;
    }
  }
}
